using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;

using Framework;

namespace SchemaMonitor
{
    [Serializable()]
    public partial class CTagType : CBaseDynamic, IComparable<CTagType>
    {
        #region Constructors
        //Public (Copy Constructor)
        public CTagType(CTagType original, CDataSrc target)
        {
            //Database Connection
            m_dataSrc = target;

            //Copy fields
            _typeAppId = original.TypeAppId;
            _typeName = original.TypeName;
            _tagIsOneToOne = original.TagIsOneToOne;
        }

        //Protected (Datareader/Dataset)
        protected CTagType(CDataSrc dataSrc, IDataReader dr) : base(dataSrc, dr) {}
        protected CTagType(CDataSrc dataSrc, DataRow     dr) : base(dataSrc, dr) {}
        #endregion

        #region Default Values
        protected override void InitValues_Auto()
        {
            //Null-Equivalent values (except String.Empty, as nulls tend to be inconvenient for string types)
            _typeId = int.MinValue;
            _typeAppId = int.MinValue;
            _typeName = string.Empty;
            _tagIsOneToOne = false;
        }
        #endregion

        #region Members
        protected int _typeId;
        protected int _typeAppId;
        protected string _typeName;
        protected bool _tagIsOneToOne;
        #endregion

        #region Properties - Column Values
        //Primary Key Column (ReadOnly)
        public int TypeId    {   get { return _typeId;   } }

        //Table Columns (Read/Write)
        public int TypeAppId    {   get { return _typeAppId; } set { _typeAppId = value; }    }
        public string TypeName    {   get { return _typeName; } set { _typeName = value; }    }
        public bool TagIsOneToOne    {   get { return _tagIsOneToOne; } set { _tagIsOneToOne = value; }    }

        //View Columns (ReadOnly)

        #endregion

        #region MustOverride Methods
        //Schema Information
        public const string TABLE_NAME      = "TagTypes";
        public const string VIEW_NAME       = "";         //Used to override this.ViewName { get }
        public const string ORDER_BY_COLS   = "TypeName";   //See the CompareTo method below (Sql-based sorting should match In-Memory sorting)
        public const string SORTING_COLUMN  = "";
        public override string TableName {    get { return TABLE_NAME; } }
        protected override string OrderByColumns {    get { return ORDER_BY_COLS; } }

        //CompareTo Interface (Default Sort Order)
        public int CompareTo(CTagType other) {   return this.TypeName.CompareTo(other.TypeName) ;  }

        //Primary Key Information
        public const string PRIMARY_KEY_NAME = "TypeId";
        protected override bool InsertPrimaryKey {  get { return false;    }   }
        protected override string PrimaryKeyName {  get { return PRIMARY_KEY_NAME;    }    }
        protected override object PrimaryKeyValue 
        {
              get { return _typeId; }
              set { _typeId = (int)value; }
        }

        //Factory Methods - Object
        protected override CBase MakeFrom(DataRow row)      {   return new CTagType(this.DataSrc, row);  }
        protected override CBase MakeFrom(IDataReader dr)   {   return new CTagType(this.DataSrc, dr);   }

        //Factory Methods - List
        protected override IList MakeList()                 {   return new CTagTypeList();               }
        protected override IList MakeList(int capacity)     {   return new CTagTypeList(capacity);       }

        //Convert from ADO to .Net
        protected override void ReadColumns(IDataReader dr)
        {
            _typeId = CAdoData.GetInt(dr, "TypeId");
            _typeAppId = CAdoData.GetInt(dr, "TypeAppId");
            _typeName = CAdoData.GetStr(dr, "TypeName");
            _tagIsOneToOne = CAdoData.GetBool(dr, "TagIsOneToOne");
        }
        protected override void ReadColumns(DataRow dr)
        {
            _typeId = CAdoData.GetInt(dr, "TypeId");
            _typeAppId = CAdoData.GetInt(dr, "TypeAppId");
            _typeName = CAdoData.GetStr(dr, "TypeName");
            _tagIsOneToOne = CAdoData.GetBool(dr, "TagIsOneToOne");
        }

        //Parameters for Insert/Update    
        protected override CNameValueList ColumnNameValues()
        {
            CNameValueList data = new CNameValueList();
            data.Add("TypeId", CAdoData.NullVal(_typeId));
            data.Add("TypeAppId", CAdoData.NullVal(_typeAppId));
            data.Add("TypeName", CAdoData.NullVal(_typeName));
            data.Add("TagIsOneToOne", CAdoData.NullVal(_tagIsOneToOne));
            return data;
        }
        #endregion

        #region Queries - SelectAll/SelectWhere (inherited methods, cast only)
        //Normally used to load the cache
        public    new CTagTypeList SelectAll()                                                                           {   return (CTagTypeList)base.SelectAll();        }
        public    new CTagTypeList SelectAll(string orderBy)                                                             {   return (CTagTypeList)base.SelectAll(orderBy); }

        //Sometimes use a custom query to load the cache
        protected new CTagTypeList SelectWhere(string colName, ESign sign, object colValue)                              {   return (CTagTypeList)base.SelectWhere(colName, sign, colValue);                  }
        protected new CTagTypeList SelectWhere(CCriteria where)                                                          {   return (CTagTypeList)base.SelectWhere(where);                                    }
        protected new CTagTypeList SelectWhere(CCriteriaList where)                                                      {   return (CTagTypeList)base.SelectWhere(where);                                    }
        protected new CTagTypeList SelectWhere(CCriteriaList where, string tableOrJoin)                                  {   return (CTagTypeList)base.SelectWhere(where, tableOrJoin, this.OrderByColumns);  }
        protected new CTagTypeList SelectWhere(CCriteriaList where, string tableOrJoin, string orderBy)                  {   return (CTagTypeList)base.SelectWhere(where, tableOrJoin, orderBy);              }
        [Obsolete("Arbitrary where-clause is not necessary portable or safe from sql injection attacks. Consider using the parameterised query interfaces (or a stored proc)")]
        protected new CTagTypeList SelectWhere(string unsafeWhereClause)                                                 {   return (CTagTypeList)base.SelectWhere(unsafeWhereClause);                        }
        protected     CTagTypeList SelectById(int typeId)                                               {   return (CTagTypeList)base.SelectById(typeId);                    }
        protected     CTagTypeList SelectByIds(List<int> ids)                                         {   return (CTagTypeList)base.SelectByIds(ids);                                      }

        //Select Queries - Paged
        protected new CTagTypeList SelectAll(  CPagingInfo pi)                                               {    return (CTagTypeList)base.SelectAll(  pi);                          }
        protected new CTagTypeList SelectWhere(CPagingInfo pi, string name, ESign sign, object value)        {    return (CTagTypeList)base.SelectWhere(pi, name, sign, value);       }
        protected new CTagTypeList SelectWhere(CPagingInfo pi, CCriteria criteria)                           {    return (CTagTypeList)base.SelectWhere(pi, criteria);                }
        protected new CTagTypeList SelectWhere(CPagingInfo pi, CCriteriaList criteria)                       {    return (CTagTypeList)base.SelectWhere(pi, criteria);                }
        protected new CTagTypeList SelectWhere(CPagingInfo pi, CCriteriaList criteria, string viewOrJoin)    {    return (CTagTypeList)base.SelectWhere(pi, criteria, viewOrJoin);    }

        //Select Queries - Transactional (Internal scope for use in cascade deletes)
        internal new CTagTypeList SelectAll(                                                                                           IDbTransaction tx)  {    return (CTagTypeList)base.SelectAll(                                                 tx);    }
        internal new CTagTypeList SelectAll(string orderBy,                                                                            IDbTransaction tx)  {    return (CTagTypeList)base.SelectAll(orderBy,                                         tx);    }
        internal new CTagTypeList SelectWhere(string columnName,               object columnValue,                                     IDbTransaction tx)  {    return (CTagTypeList)base.SelectWhere(columnName,              columnValue,          tx);    }
        internal new CTagTypeList SelectWhere(string columnName,   ESign sign, object columnValue,                                     IDbTransaction tx)  {    return (CTagTypeList)base.SelectWhere(columnName,    sign,     columnValue,          tx);    }
        internal new CTagTypeList SelectWhere(                             CCriteria     criteria,                                     IDbTransaction tx)  {    return (CTagTypeList)base.SelectWhere(               criteria,                       tx);    }
        internal new CTagTypeList SelectWhere(                             CCriteriaList criteria,                                     IDbTransaction tx)  {    return (CTagTypeList)base.SelectWhere(               criteria,                       tx);    }
        internal new CTagTypeList SelectWhere(                             CCriteriaList criteria, string tableOrJoin,                 IDbTransaction tx)  {    return (CTagTypeList)base.SelectWhere(               criteria, tableOrJoin,          tx);    }
        internal new CTagTypeList SelectWhere(                             CCriteriaList criteria, string tableOrJoin, string orderBy, IDbTransaction tx)  {    return (CTagTypeList)base.SelectWhere(               criteria, tableOrJoin,          tx);    }
        internal     CTagTypeList SelectById(int typeId,                                                              IDbTransaction tx)  {    return (CTagTypeList)base.SelectById(typeId,                         tx);    }
        internal     CTagTypeList SelectByIds(List<int> ids,                                                        IDbTransaction tx)  {    return (CTagTypeList)base.SelectByIds(ids,                                           tx);    }

        //Select Queries - Stored Procs
        protected new CTagTypeList MakeList(string storedProcName,                           IDbTransaction txOrNull)    {   return (CTagTypeList)base.MakeList(storedProcName,             txOrNull);  }
        protected new CTagTypeList MakeList(string storedProcName, object[] parameters,      IDbTransaction txOrNull)    {   return (CTagTypeList)base.MakeList(storedProcName, parameters, txOrNull);  }
        protected new CTagTypeList MakeList(string storedProcName, CNameValueList parameters,IDbTransaction txOrNull)    {   return (CTagTypeList)base.MakeList(storedProcName, parameters, txOrNull);  }
        protected new CTagTypeList MakeList(string storedProcName, List<object> parameters,  IDbTransaction txOrNull)    {   return (CTagTypeList)base.MakeList(storedProcName, parameters, txOrNull);  }
        protected new CTagTypeList MakeList(string storedProcName, int param1,               IDbTransaction txOrNull)    {   return (CTagTypeList)base.MakeList(storedProcName, param1,     txOrNull);  }
        protected new CTagTypeList MakeList(string storedProcName, string param1,            IDbTransaction txOrNull)    {   return (CTagTypeList)base.MakeList(storedProcName, param1,     txOrNull);  }

        //Query Results
        protected new CTagTypeList MakeList(DataSet              ds) { return (CTagTypeList)base.MakeList(ds);        }
        protected new CTagTypeList MakeList(DataTable            dt) { return (CTagTypeList)base.MakeList(dt);        }
        protected new CTagTypeList MakeList(DataRowCollection  rows) { return (CTagTypeList)base.MakeList(rows);      }
        protected new CTagTypeList MakeList(IDataReader          dr) { return (CTagTypeList)base.MakeList(dr);        }
        protected new CTagTypeList MakeList(object           drOrDs) { return (CTagTypeList)base.MakeList(drOrDs);    }
        protected new CTagTypeList MakeList(byte[]             gzip) { return (CTagTypeList)base.MakeList(gzip);      }
        #endregion

        #region Queries - SelectBy[FK] (user-nominated fk/bool columns)
        //Note: These methods should only be used for cascade-deletes, or initialising the cache. Use CTagType.Cache.GetBy... for reqular queries

        //Non-Paged
        protected CTagTypeList SelectByYpeAppId(int typeAppId)    {    return SelectWhere(new CCriteriaList("TypeAppId", typeAppId));    }
        protected CTagTypeList SelectByAgIsOneToOne(bool tagIsOneToOne)    {    return SelectWhere(new CCriteriaList("TagIsOneToOne", tagIsOneToOne));    }

        //Paged
        protected CTagTypeList SelectByYpeAppId(CPagingInfo pi, int typeAppId)    {    return SelectWhere(pi, new CCriteriaList("TypeAppId", typeAppId));    }
        protected CTagTypeList SelectByAgIsOneToOne(CPagingInfo pi, bool tagIsOneToOne)    {    return SelectWhere(pi, new CCriteriaList("TagIsOneToOne", tagIsOneToOne));    }

        //Count
        protected int SelectCountByYpeAppId(int typeAppId)   {   return SelectCount(new CCriteriaList("TypeAppId", typeAppId));     }
        protected int SelectCountByAgIsOneToOne(bool tagIsOneToOne)   {   return SelectCount(new CCriteriaList("TagIsOneToOne", tagIsOneToOne));     }

        //Transactional
        internal CTagTypeList SelectByYpeAppId(int typeAppId, IDbTransaction tx)    {    return SelectWhere(new CCriteriaList("TypeAppId", typeAppId), tx);    }
        internal CTagTypeList SelectByAgIsOneToOne(bool tagIsOneToOne, IDbTransaction tx)    {    return SelectWhere(new CCriteriaList("TagIsOneToOne", tagIsOneToOne), tx);    }
        #endregion

        #region Static - Cache Implementation
        public static CTagTypeList Cache
        {
            get
            {
                CTagTypeList cache = (CTagTypeList)CCache.Get(CACHE_KEY);
                if (cache == null)
                {
                    lock (typeof(CTagTypeList))
                    {
                        cache = (CTagTypeList)CCache.Get(CACHE_KEY);
                        if (cache == null)
                        {
                            cache = LoadCache();
                            CTagType.Cache = cache;
                        }
                    }
                }
                return cache;
            }
            set
            {
                SetCache(value);   //Not locked, because cache gets cleared at anytime anyway
            }
        }

        //Change Management:
        //Clone, modify, and then replace the cache (threadsafe for anything iterating the collection)
        //Note that internal indices are dicarded each time unless handled in constructor and add/remove overrides
        protected override void CacheDelete()
        {
            if (CacheIsNull)
                return;

            lock (typeof(CTagTypeList))
            {
                CTagTypeList temp = new CTagTypeList(Cache);
                int size = temp.Count;
                temp.Remove(this);
                if (size == temp.Count) //Remove might fail if cache was refreshed with new instances. Use old index
                    temp.Remove(CacheGetById(temp));
                Cache = temp;
            }
        }
        protected override void CacheInsert()
        {
            if (CacheIsNull)
                return;

            lock (typeof(CTagTypeList))
            {
                CTagTypeList temp = new CTagTypeList(Cache);
                temp.Add(this);
                SetCache(temp);
            }
        }
        protected override void CacheUpdate()
        {
            if (CacheIsNull)
                return;

            lock (typeof(CTagTypeList))
            {
                CTagTypeList temp = new CTagTypeList(Cache);
                if (!temp.Contains(this))
                {
                    temp.Remove(CacheGetById(temp));
                    temp.Add(this);
                }
                SetCache(temp);
            }
        }
        protected override void CacheClear()
        {
            SetCache(null);
        }
        protected static bool CacheIsNull
        {
            get
            {
                return null == CCache.Get(CACHE_KEY);
            }
        }
        #endregion
        #region ToXml
        protected override void ToXml_Autogenerated(System.Xml.XmlWriter w)
        {
            Store(w, "TypeId", this.TypeId);
            Store(w, "TypeAppId", this.TypeAppId);
            Store(w, "TypeName", this.TypeName);
            Store(w, "TagIsOneToOne", this.TagIsOneToOne);
        }
        #endregion

    }
}
